import Store from '../store'
import axios from 'axios'
import Qs from 'qs'
import router from 'vue-router'
import { SessionStorage } from 'quasar'
import {
  baseURL,
  POST,
  PUT,
  PATCH,
  DELETE,
  MSGCODE_SUCCESS,
  MSGCODE_SYSTEM_EX,
  MSGCODE_PARAMETER_EX,
  MSGCODE_BUS_EX,
  MSGCODE_DATA_EX,
  MSGCODE_INTERFACE_EX,
  MSGCODE_VALIDATE_EX,
  MSGCODE_UPLOAD_EX
} from '../utils/consts'
console.log(Store, 1111)
const store = new Store()
// const baseConfig = axios => {
//   axios.defaults.baseURL = baseURL
// }
const transformRequest = axios => {
  console.log('11111111111')
  axios.defaults.transformRequest = [
    function (data, headers) {
      // // 添加 Authorization 头信息
      // Object.assign(headers, auth.getAuthHeader())
      headers['Authorization'] = SessionStorage.getItem('token')
      if (data === undefined) {
        return
      }
      if (data.Qsjson) {
        headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
        delete data.Qsjson
        return Qs.stringify(data, { indices: false })
      }
      if (data.emulateFile) {
        headers['Content-Type'] = 'multipart/form-data;charset=UTF-8'
        delete data.emulateFile
        return data.emulateFile
      }
      if (data.emulateJSON) {
        headers['Content-Type'] = 'application/json;charset=UTF-8'
        delete data.emulateJSON
        return JSON.stringify(data)
      }
      if (data.emulateQS) {
        headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
        delete data.emulateQS
        return Qs.stringify(data)
      }
    }
  ]
}
const addRequestInterceptors = axios => {
  axios.interceptors.request.use(
    function (config) {
      if (config.useLoadLayer) {
        store.commit('loading/CHANGE_LOAD_SHOW_STATE', true)
      }

      if (config.useAjaxBar) {
        store.commit('loading/CHANGE_AJAXBAR_SHOW_STATE', true)
      }
      // console.log(config.data !== null)
      // for (let i in config.headers) {
      //   var a = config.headers[i]['Content-Type']
      // }
      // if (config.data !== null && config.method === PUT && a === 'application/x-www-form-urlencoded') {
      //   store.commit('axios/MSGCODE_PARAMETER_EX', 'formdata只支持get/post')
      //   return false
      // }
      return config
    },
    function (error) {
      store.commit('loading/CHANGE_LOAD_SHOW_STATE', false)
      store.commit('loading/CHANGE_AJAXBAR_SHOW_STATE', false)
      console.error('[request error] ' + error)
      return Promise.reject(error)
    }
  )
  return axios
}
// 登陆报错
const addResponseInterceptors = axios => {
  axios.interceptors.response.use(
    function (response) {
      console.log(response.data.msgCode)
      if (response.data.msgCode === 500) {
        console.log(router.replace)
        // router.beforeEach((to, from, next) => {
        //   next({
        //     path: '/account/login',
        //     query: { redirect: to.fullPath }
        //   })
        // })
      }
      store.commit('loading/CHANGE_LOAD_SHOW_STATE', false)
      store.commit('loading/CHANGE_AJAXBAR_SHOW_STATE', false)
      return Promise.resolve(response)
    },
    function (error) {
      console.log(error)
      store.commit('loading/CHANGE_LOAD_SHOW_STATE', false)
      store.commit('loading/CHANGE_AJAXBAR_SHOW_STATE', false)
      console.error('[response error] ' + error)
      return Promise.reject(error)
    }
  )
}
const accessInVue = (Vue, axios, name = '$http') => {
  Vue.prototype[name] = axios
}
export const config = (Vue, name) => {
  // baseConfig(axios)
  transformRequest(axios)
  addRequestInterceptors(axios)
  addResponseInterceptors(axios)
  accessInVue(Vue, axios, name)
}

export const api = ({
  baseUrl = baseURL,
  url,
  method,
  params = {},
  emulateJSON = false,
  emulateQS = false,
  emulateFile = false,
  Qsjson = false,
  useLoadLayer,
  useAjaxBar,
  useNotify,
  timeout = false,
  successCallback,
  errorCallback
}) => {
  let reqConf = { method, url, useLoadLayer, useAjaxBar, useNotify }
  if ((method === POST || method === PUT || method === PATCH || method === DELETE) && emulateJSON) {
    console.log('444444444444')
    params.emulateJSON = true
  }
  if ((method === POST || method === PUT || method === PATCH || method === DELETE) && Qsjson) {
    params.Qsjson = true
  }
  if ((method === POST || method === PUT || method === PATCH || method === DELETE) && emulateFile) {
    params.emulateFile = true
  }
  if ((method === POST || method === PUT || method === PATCH || method === DELETE) && emulateQS) {
    params.emulateQS = true
  }
  reqConf[(method === POST || method === PUT || method === PATCH || method === DELETE) ? 'data' : 'params'] = params

  if (baseUrl) {
    axios.defaults.baseURL = baseUrl
  }
  if (timeout) {
    axios.defaults.timeout = 100000
  }
  return axios(reqConf)
    .then(response => {
      let msgCode = response.data.msgCode
      if (msgCode + '' === MSGCODE_SUCCESS + '') {
        // 业务级成功
        if (successCallback) {
          if (useNotify) {
            store.commit('axios/AJAX_NOTIFY_SUCCESS')
          }
          return successCallback(response.data) // 这里整个data返回，以便后续有其它额外的处理操作
        }
      } else {
        // 业务级失败
        if (msgCode === MSGCODE_SYSTEM_EX && useNotify) {
          // 500
          store.commit('axios/AJAX_NOTIFY_SYSTEM_EX')
        } else if (msgCode === MSGCODE_PARAMETER_EX && useNotify) {
          // 501
          store.commit('axios/MSGCODE_PARAMETER_EX', response.data.msg)
        } else if (msgCode === MSGCODE_BUS_EX && useNotify) {
          // 502
          store.commit('axios/MSGCODE_BUS_EX', response.data.msg)
        } else if (msgCode === MSGCODE_DATA_EX && useNotify) {
          // 503
          store.commit('axios/AJAX_NOTIFY_SYSTEM_EX', response.data.msg)
        } else if (msgCode === MSGCODE_INTERFACE_EX && useNotify) {
          // 504
          store.commit('axios/AJAX_NOTIFY_SYSTEM_EX')
        } else if (msgCode === MSGCODE_VALIDATE_EX && useNotify) {
          // 505
          store.commit('axios/AJAX_NOTIFY_SYSTEM_EX', response.data.msg)
        } else if (msgCode === MSGCODE_UPLOAD_EX && useNotify) {
          // 506
          store.commit('axios/AJAX_NOTIFY_SYSTEM_EX')
        } else {
          if (errorCallback) {
            return errorCallback(response.data)
          }
        }
      }
    })
    .catch(error => {
      if (error.response) {
        // 服务端异常（返回的 HTTP 状态码非 2xx）
        errorCallback && errorCallback(error)
      } else {
        // 客户端代码异常（request 预处理、 successCallback 执行报错）或 请求超时
        console.error('[Error]', error.message)
      }
      console.error('[Error.config]', error.config)
    })
}
window.addEventListener('unhandledrejection', function (e) {
  console.log('被抛到全局未捕获的异常', e)
})
